﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BDAlertorApp.Util
{
    /// <summary>
    /// 字符串工具类
    /// </summary>
    public class StringUtil
    {
        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static String Bytes2HexString(byte[] bytes)
        {
            if (bytes == null || (bytes != null && bytes.Length == 0))
            {
                return "";
            }

            string hexStr = string.Empty;
            foreach (var b in bytes)
            {
                //转换成16进制字符串
//                hexStr += b.ToString("X2");
                hexStr += Convert.ToString(b, 16);
            }
            return hexStr.ToUpper();
        }

        /// <summary>
        /// 字符串转16进制字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String String2HexString(String str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return "";
            }
            byte[] bytes = null;
            try
            {
                bytes = System.Text.Encoding.Default.GetBytes(str);
            }
            catch (Exception e)
            {

            }

            return Bytes2HexString(bytes);
        }

        /// <summary>
        /// 16进制字符串转字节数组
        /// </summary>
        /// <param name="hexStr"></param>
        /// <returns></returns>
        public static byte[] HexString2Bytes(String hexStr)
        {
            if (String.IsNullOrEmpty(hexStr))
            {
                return null;
            }

            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hexStr.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hexStr.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
                }
                catch (Exception e)
                {

                }
            }

            return bytes;
        }
        /// <summary>
        ///  16进制字符串转字符串
        /// </summary>
        /// <param name="hexStr"></param>
        /// <returns></returns>
        public static String HexString2String(String hexStr)
        {
            if (String.IsNullOrEmpty(hexStr))
            {
                return "";
            }
            byte[] bytes = HexString2Bytes(hexStr);

            return System.Text.Encoding.Default.GetString(bytes);
        }
    }
}
